package com.ruoyi.chat.service.impl;

import com.ruoyi.chat.LongConnection.model.msg.FileMsg;
import com.ruoyi.chat.service.IMinioService;
import com.ruoyi.chat.util.GetContentType;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Objects;
import java.util.UUID;

@Service
public class MinioService implements IMinioService {
    @Autowired
    MinioClient client;
    @Override
    public String setFile(FileMsg fileMsg) throws Exception {
        //获取文件的后缀名 例如.jpg
        String suffix = Objects.requireNonNull(fileMsg.getFileName()).substring(fileMsg.getFileName().lastIndexOf("."));
        //使用默认时区和语言环境获得一个日历。
        Calendar rightNow = Calendar.getInstance();
        Integer year = rightNow.get(Calendar.YEAR);
        Integer month = rightNow.get(Calendar.MONTH) + 1; //第一个月从0开始，所以得到月份＋1
        Integer day = rightNow.get(Calendar.DAY_OF_MONTH);
        String bucket = year + "-" + month;
        boolean exists = client.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
        if (!exists) {
            client.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
        }
        InputStream go = new ByteArrayInputStream(fileMsg.getStream());
        String fileName = UUID.randomUUID() + suffix;
        client.putObject(PutObjectArgs.builder().bucket(bucket).stream(go, go.available(), -1).object(fileName).contentType(GetContentType.getContentType(suffix)).build());
        return bucket + "/" + fileName;
    }
}
